package org.wattdepot.gdata.kukuicup.updater.energybaselines;

import java.util.Timer;
import java.util.TimerTask;
import org.wattdepot.gdata.kukuicup.service.GDataService;
import org.wattdepot.gdata.kukuicup.service.WattDepotService;
import org.wattdepot.gdata.kukuicup.updater.Updater;

/**
 * Updates a spreadsheet containing hourly baseline energy consumption data. 
 * @author Philip Johnson
 */
public class HourlyEnergyBaselinesUpdater extends Updater {
  
  private static final String delayKey = "hourly.energy.baselines.delay";
  private static final String defaultSpreadsheetName = "HourlyEnergyBaselines";
  private static final String spreadsheetNameKey = "hourly.energy.baselines.spreadsheet";

  /**
   * Constructs this updater service. 
   * @param wattDepotService The WattDepot service used to get the energy data. 
   * @param gdataService The GData service used to  find the spreadsheets. 
   * @throws Exception If problems occur. 
   */
  public HourlyEnergyBaselinesUpdater(WattDepotService wattDepotService, GDataService gdataService) 
  throws Exception {
    // allow the user to generate this data in a different spreadsheet by providing a property.
    super(wattDepotService.getProperties().getProperty(spreadsheetNameKey, defaultSpreadsheetName),
        wattDepotService, gdataService);
    logNonDefaultSpreadsheet(spreadsheetNameKey);
  }

  /**
   * This task generates a separate HourlyEnergyBaselinesTask for each source.
   * Each task runs exactly once, gets the hourly baseline data for 
   * its source, and writes those values out to the hourly baseline spreadsheet.
   */
  @Override
  public void run() {
    int delay = 0;
    int delayInterval =  wattDepotService.getProperties().getIntegerProperty(delayKey, 15);
    System.out.format("Hourly baselines task delay is %s secs.%n", delayInterval);
    for (String sourceName : sourceNames) {
      Timer timer = new Timer();
      TimerTask task = new HourlyEnergyBaselinesTask(wattDepotService, gdataService, 
          spreadsheetURL, sourceName, isVirtual(sourceName), getRow(sourceName));
      timer.schedule(task, delay);
      delay += delayInterval * 1000;
    }
  }
}
